<?php
namespace App\Http\Controllers\Api\Resource;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class Qiniu extends Controller
{

    protected static function disk ($download=false)
    {
        return Storage::disk($download ? 'download' : 'sd');
    }


    protected static function domain ($download=false)
    {
        $download = $download ? 'download' : 'sd';
        return config('filesystems.disks.'.$download.'.domain');
    }





    /**
     * 文件夹是否合法
     * @param string $dir 文件夹名称
     * */
    static function dir ($dir):bool
    {
        return in_array($dir, config('filesystems.disks.sd.dir', [
            'product'
        ]));
    }



    public function upload ()
    {

    }


    public function download ()
    {

    }


    /**
     * 获取七牛Token
     * @param string $dir 文件夹
     * @param int $exp 过期时间，默认3600。
     * @param bool $download 默认false
     */
    public function token (Request $req)
    {
        $dir = $req->get('dir');
        if (!static::dir($dir)) {
            return self::resFail('文件夹不合法。');
        }

        $disk = self::disk($req->get('download'));
        $exp = (int)$req->get('exp', 3600);
        $token = $disk->getUploadToken(null, $exp);

        return self::resSuccess('Token已生成。', [
            'token' => $token,
            'domain' => self::domain($req->get('download')),
            'key' => $dir,
            'exp' => $exp+time(),
        ]);
    }


}
